import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/models/app_model.dart';
import 'package:flutter_rtk/models/user_info_model.dart';
import 'package:flutter_rtk/service/store_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../core/flutter_api.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key, required this.title, required this.url});

  final String title;
  final String url;

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  int _progress = 0;
  late WebViewController _controller;

  // 是否显示右上角close btn
  bool displayCloseButton = false;

  // 是否显示appbar
  bool displayAppbar = false;

  // 是否本地url
  bool isLocalUrl = false;

  @override
  void initState() {
    super.initState();
    try {
      var uri = Uri.dataFromString(widget.url);
      // 是否本地url
      if ("1" == (uri.queryParameters['isLocal'] ?? "0")) {
        setState(() {
          isLocalUrl = true;
        });
      }
      // back=1表示可以回退
      if ("1" == (uri.queryParameters['back'] ?? "0")) {
        setState(() {
          displayCloseButton = true;
        });
      }
      // 是否展示壳子头部，默认是不展示的(h5有自己的头部)
      if ("1" == (uri.queryParameters['showAppbar'] ?? "0")) {
        setState(() {
          displayAppbar = true;
        });
      }
    } catch (e) {
      //
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: displayAppbar
          ? mainAppBar(
              title: widget.title,
              rightButton: buildRightBtnByDisplayValue(context),
              leftButton: IconButton(
                onPressed: () async {
                  bool canGoBack = await _controller.canGoBack();
                  if (displayCloseButton && canGoBack) {
                    await _controller.goBack();
                  } else {
                    // ignore: use_build_context_synchronously
                    Navigator.pop(context);
                  }
                },
                icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
              ),
            )
          : null,
      body: SafeArea(
        top: true,
        child: Stack(
          children: [
            SizedBox(
              width: double.infinity,
              height: double.infinity,
              child: Consumer2<UserInfoModel, AppModel>(builder: (context, user, app, child) {
                return WebView(
                  backgroundColor: Colors.white,
                  onWebViewCreated: (controller) {
                    _controller = controller;
                    if (isLocalUrl) {
                      _controller.loadFile(widget.url);
                      // _controller.loadFile("/data/data/com.rtk.flutter_rtk/app_flutter/index.html");
                    }
                  },
                  onPageStarted: (v) {
                    setState(() {
                      _progress = 0;
                    });
                  },
                  onProgress: (v) {
                    setState(() {
                      _progress = v;
                    });
                  },
                  onPageFinished: (v) {
                    setState(() {
                      _progress = 100;
                    });
                  },
                  initialUrl: widget.url,
                  javascriptChannels: {
                    JavascriptChannel(
                      name: 'FlutterApi',
                      onMessageReceived: (JavascriptMessage data) {
                        FlutterApi.executeRespString(context, _controller, data.message);
                      },
                    ),
                    JavascriptChannel(
                      name: 'FlutterApi2',
                      onMessageReceived: (JavascriptMessage data) {
                        FlutterApi.executeRespJson(context, _controller, data.message);
                      },
                    ),
                  },
                  javascriptMode: JavascriptMode.unrestricted,
                  initialCookies: [
                    WebViewCookie(name: 'access_token', value: StoreService.to.getString(AppConstants.token), domain: _handleDomain()),
                    WebViewCookie(name: 'refresh_token', value: user.loginInfo?.refreshToken ?? "", domain: _handleDomain()),
                    WebViewCookie(name: 'user_info', value: jsonEncode(user.userInfo), domain: _handleDomain()),
                    WebViewCookie(name: 'current_project', value: jsonEncode(app.currentProjectInfo), domain: _handleDomain()),
                  ],
                );
              }),
            ),
            buildLinearProgressBarByProgressValue(),
          ],
        ),
      ),
    );
  }

  Widget buildRightBtnByDisplayValue(BuildContext context) {
    return displayCloseButton ? IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close)) : const SizedBox.shrink();
  }

  buildLinearProgressBarByProgressValue() {
    if (_progress >= 100) {
      return const SizedBox.shrink();
    }
    return SizedBox(
      width: double.infinity,
      height: 5.h,
      child: LinearProgressIndicator(
        color: Colors.orange,
        backgroundColor: Colors.white,
        value: _progress.toDouble(),
      ),
    );
  }

  @override
  void didUpdateWidget(covariant WebViewPage oldWidget) {
    if (oldWidget.url == widget.url) {
      return;
    }
    super.didUpdateWidget(oldWidget);
  }

  _handleDomain() {
    String domain = StoreService.to.getString(AppConstants.baseUrl);
    try {
      return Uri.parse(domain).host;
    } catch (e) {
      //
    }
    if (domain.contains("http://")) {
      domain = domain.substring(domain.indexOf("http://") + 7, domain.length);
    }
    if (domain.contains("https://")) {
      domain = domain.substring(domain.indexOf("https://") + 8, domain.length);
    }
    if (domain.contains(":")) {
      domain = domain.substring(0, domain.indexOf(":"));
    }
    return domain;
  }
}
